﻿
using WHLRDF.ORM;
using WHLRDF.ORG.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using WHLRDF.Application.Model;
using WHLRDF.Application.BLL;

namespace WHLRDF.ORG.BLL
{
    public enum JobFunctionType
    {
        JobFunction=0,
        SubChart=1
    }
    public class OrgChartService : SerivceBase, IOrgChartService
    {
        private static readonly object locked = new object();
        /// <summary>
        /// 接口实例
        /// </summary>
        public const string CACHE_ORGCHART_IEVENTHANDLER = "CACHE_ORGCHART_IEVENTHANDLER";
        /// <summary>
        /// 组织机构保存路径
        /// </summary>
        public static string RootPath
        {
            get
            {
                return ApplicationEnvironments.BaseDirectory + ApplicationEnvironments.Site.ConfigPath.Where(x=>x.RootKey== ConfigPathKeyType.config).FirstOrDefault().Path + "/orgchart/";
            }
        }

        /// <summary>
        /// 组织机构保存路径
        /// </summary>
        public string CheckOutPath
        {
            get
            {
                return RootPath + "orgchart/checkout/";
            }
        }

        #region 部门操作
        /// <summary>
        /// 获取部门的基本信息
        /// </summary>
        /// <param name="deptid"></param>
        /// <param name="isload">是否页面加载</param>
        /// <returns></returns>
        public OrgChartEntity GetOrgById(string deptid)
        {
            OrgChartEntity orgEntity = null;
            
            string strError = "";
            orgEntity = ReadOrgChart(deptid);
            if (orgEntity == null)
            {
                orgEntity = GetOrgById(deptid, ref strError);
            }
            if (orgEntity != null)
            {
                if (orgEntity.Department.IsCheckOut && orgEntity.Department.CheckOutUserId.Equals(ApplicationEnvironments.DefaultSession.UserId))
                {
                    orgEntity.Department.IsEdited = true;
                }
            }
            
            return orgEntity;
        }


        /// <summary>
        /// 加载部门组织架构数据
        /// </summary>
        /// <param name="deptid"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public OrgChartEntity GetOrgById(string deptid, ref string strError)
        {
            var jobService = new JobFunctionService();
            var deptService = new DepartmentService();
            OrgChartEntity orgEntity = new OrgChartEntity();
            var deptEntity = deptService.GetById(deptid);
            if (deptEntity == null)
            {
                strError = "部门未找到，参数错误";
                return null;
            }
            orgEntity.Department = deptEntity;
            if (deptEntity != null)
            {
                if (orgEntity.JobData == null || orgEntity.JobData.Count <= 0)
                {
                    List<JobFunctionEntity> lstJob = jobService.GetAllByDeptId(deptid);
                    if (lstJob == null || lstJob.Count <= 0)
                    {
                        lstJob = new List<JobFunctionEntity>();
                        lstJob.Add(new JobFunctionEntity()
                        {
                            JobFunctionId = jobService.CreateJobFunctionIdByDeptId(deptid, ref strError),
                            OrgId = deptEntity.OrgId,
                            DepartmentId = deptEntity.DepartmentId,
                            JobFunctionType = 0,
                            JobFunctionName = "员工",
                            SourceName = "员工",
                            OrderNum = 1,
                            ParentId = "",
                            IsPrimary = true
                        });
                    }

                    orgEntity.JobData = lstJob;
                }
                orgEntity.Department = deptEntity;
               // xmlData = JSONHelper.ToJson(orgEntity);
                this.SaveFile(orgEntity,ref strError);
            }
            return orgEntity;
        }
        /// <summary>
        /// 部门编辑
        /// </summary>
        /// <param name="entity">部门实体</param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool DeptSave(ref DepartmentEntity deptEntity, ref string strError)
        {
            return SaveDepartment(ref deptEntity, ref strError);
        }

        /// <summary>
        /// 保存临时部门
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool SaveDepartment(ref DepartmentEntity deptEntity, ref string strError)
        {
            List<OrgChartEntity> lstDept = GetTempChartEntities();
            if (ExistDeptment(deptEntity, lstDept, ref strError))
            {
                return false;
            }
            string deptId = deptEntity.DepartmentId;
            if (string.IsNullOrWhiteSpace(deptEntity.DepartmentId))
            {
                deptEntity.DepartmentId= SerialService.CreateSerialNo(DepartmentService.Department_Identity_Num, null, ref strError);
            }
           var orgChart=  this.ReadOrgChart(deptId);
            if (orgChart == null)
            {
                orgChart = new OrgChartEntity();
                orgChart.Department = deptEntity;
                orgChart.Department.IsCheckOut = true;
                orgChart.Department.IsEdited = true;
                orgChart.Department.CheckOutUserId = ApplicationEnvironments.DefaultSession.UserId;
                orgChart.Department.IsNewAdd = true;
                orgChart.Department.icon = "fa fa-user";
            }
            if (orgChart.OrgEntity == null)
            {
                orgChart.OrgEntity = this.GetById<OrganizationsEntity>(orgChart.Department.OrgId);
            }
            orgChart.Department.ParentId = string.IsNullOrEmpty(orgChart.Department.ParentId) ? "" : orgChart.Department.ParentId;
            orgChart.Department.DepartmentCode = deptEntity.DepartmentCode;
            orgChart.Department.DepartmentLevel = deptEntity.DepartmentLevel;
            orgChart.Department.DepartmentName = deptEntity.DepartmentName;
            orgChart.Department.OrderNum = deptEntity.OrderNum;
            orgChart.Department.Remark = deptEntity.Remark;
            orgChart.Department.LastModifyDate = DateTime.Now;
            orgChart.Department.LastModifyUserId = ApplicationEnvironments.DefaultSession.UserId;
            if (orgChart != null && (orgChart.JobData == null || orgChart.JobData.Count <= 0))
            {
                orgChart.JobData = new List<JobFunctionEntity>();
                var jobService = new JobFunctionService();
                orgChart.JobData.Add(new JobFunctionEntity()
                {
                    JobFunctionId = jobService.CreateJobFunctionIdByDeptId(orgChart.Department.DepartmentId, ref strError),
                    OrgId = orgChart.Department.OrgId,
                    DepartmentId = orgChart.Department.DepartmentId,
                    JobFunctionType = 0,
                    JobFunctionName = "员工",
                    SourceName = "员工",
                    OrderNum = 1,
                    ParentId = "",
                    IsPrimary = true
                });
            }
            deptEntity = orgChart.Department;
            return this.SaveFile(orgChart,ref strError);
        }

        /// <summary>
        /// 执行保存动作，存储物理文件以及更新缓存
        /// </summary>
        /// <param name="orgChart"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool SaveFile(OrgChartEntity orgChart, ref string strError)
        {
            lock (locked)
            {
                if (!orgChart.Department.IsCheckOut || !orgChart.Department.CheckOutUserId.Equals(ApplicationEnvironments.DefaultSession.UserId))
                {
                    strError = "部门尚未迁出，无法修改";
                    return false;
                }
                if(orgChart.OrgEntity==null)
                {
                    orgChart.OrgEntity=this.GetById<OrganizationsEntity>(orgChart.Department.OrgId);
                }
                string filePath = CheckOutPath + orgChart.Department.DepartmentId + ".json";
                FileInfo fileInfo = new FileInfo(filePath);
                if (!fileInfo.Exists)
                {
                    if (!fileInfo.Directory.Exists)
                    {
                        fileInfo.Directory.Create();
                    }
                }
                FileHelper.WriteLine(filePath, orgChart.ToJson());
           }
            return true;
        }

        /// <summary>
        /// 验证新增的部门是
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="newAddLstEntity"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        private bool ExistDeptment(DepartmentEntity entity, List<OrgChartEntity> orgCharts, ref string strError)
        {
            OrgChartEntity result = null;
            if (orgCharts == null || orgCharts.Count <= 0)
            {
                return false;
            }
            if (!string.IsNullOrWhiteSpace(entity.DepartmentCode))
            {
                 result = orgCharts.Where(x => x.Department.DepartmentId != entity.DepartmentId && x.Department.DepartmentCode == entity.DepartmentCode && x.Department.DepartmentId != entity.DepartmentId).FirstOrDefault();
                if (result != null)
                {
                    strError = "【" + entity.DepartmentCode + "】" + "已存在";
                    return true;
                }
            }
            result = orgCharts.Where(x => x.Department.ParentId == entity.ParentId && x.Department.DepartmentId != entity.DepartmentId && x.Department.DepartmentName == entity.DepartmentName).FirstOrDefault();
            if (result != null)
            {
                strError = "【" + entity.DepartmentName + "】" + "已存在";
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <returns></returns>
        public List<OrgChartEntity> GetTempChartEntities()
        {
            List<OrgChartEntity> entities = new List<OrgChartEntity>();
            lock (locked)
            {

                DirectoryInfo directoryInfo = new DirectoryInfo(CheckOutPath);
                if (!directoryInfo.Exists)
                {
                    return null;
                }
                FileInfo[] files = directoryInfo.GetFiles();
                foreach (var file in files)
                {
                    var entity = ReadOrgChart(file.Name.ToLower().Replace(".json",""));
                    if (entity != null)
                    {
                        entities.Add(entity);
                    }
                }
            }
            return entities;
          
        }


        public OrgChartEntity ReadOrgChart(string deptid)
        {
            lock (locked)
            {
                 string filePath = CheckOutPath+deptid+".json";
                 if(File.Exists(filePath))
                 {
                    string chartData =FileHelper.ReadLine(filePath);
                    if (!string.IsNullOrWhiteSpace(chartData))
                    {
                        var entity = JSONHelper.FromJson<OrgChartEntity>(chartData);
                        return entity;
                    }
                 }
            }
            return null;
        }


        /// <summary>
        /// 删除临时部门
        /// </summary>
        /// <param name="id">部门id</param>
        /// <returns></returns>
        public bool TempDeptDelete(string id)
        {
            if (File.Exists(CheckOutPath + id + ".json"))
            {
                FileHelper.Delete(CheckOutPath + id + ".json");
            }
            return true;
        }
        #endregion

        #region 迁入迁出
        /// <summary>
        /// 迁出
        /// </summary>
        /// <param name="deptid"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool CheckOut(string deptid, ref string strError)
        {
            var deptEntity = this.GetById<DepartmentEntity>(deptid);
            if (deptEntity == null)
            {
                strError = "参数错误，无法执行操作";
                return false;
            }
            if (deptEntity.IsCheckOut)
            {
                strError = "部门已迁出，无需迁出";
                return false;
            }
            deptEntity.IsCheckOut = true;
            deptEntity.CheckOutUserId = ApplicationEnvironments.DefaultSession.UserId;
            deptEntity.CheckOutIp = ApplicationEnvironments.DefaultSession.IPAddress;
            var logService = new DeptCheckLogService();
            OrgChartEntity orgEntity =null;
          
            if (!string.IsNullOrWhiteSpace(deptEntity.Chart))
            {
                orgEntity = JSONHelper.FromJson<OrgChartEntity>(deptEntity.Chart);
            }
            if(orgEntity==null)
            {
                orgEntity = new OrgChartEntity();
                orgEntity.JobData = new JobFunctionService().GetAllByDeptId(deptEntity.DepartmentId);
            }
            if( orgEntity.OrgEntity==null)
            {
                  orgEntity.OrgEntity=this.GetById<OrganizationsEntity>(deptEntity.OrgId);        
            }
          
            orgEntity.Department = deptEntity;
            if (!OnDeptEventHandler("CheckOut", ref orgEntity, ref strError))
            {
                return false;
            }
            using (var tran = DbRepository.Begin())
            {
                try
                {
                    DbRepository.SaveOrUpdate(deptEntity);
                    var logEntity = logService.Save(deptEntity.DepartmentId, deptEntity.DepartmentName, 0, ref strError);
                    DbRepository.SaveOrUpdate<DeptCheckLogEntity>(logEntity);
                    DbRepository.Commit();
                }
                catch (Exception ex)
                {
                    DbRepository.Rollback();
                    throw ex;
                }
            }
            return this.SaveFile(orgEntity, ref strError);
        }

        /// <summary>
        /// 部门迁入
        /// </summary>
        /// <param name="deptid"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool CheckIn(string deptid, ref string strError)
        {
            var deptService = new DepartmentService();
         
           
            OrgChartEntity orgEntity = this.ReadOrgChart(deptid);
            if (orgEntity == null || orgEntity.Department == null || orgEntity.JobData == null || orgEntity.JobData.Count <= 0)
            {
                strError = "数据格式错误，无法转换";
                return false;
            }
            if (!orgEntity.Department.IsCheckOut || orgEntity.Department.CheckOutUserId != ApplicationEnvironments.DefaultSession.UserId)
            {
                strError = "对不起，您无权操作";
                return false;
            }
            var jobService = new JobFunctionService();
            if (deptService.ExistDept(orgEntity.Department, ref strError))
            {
                return false;
            }

            var jobAll = jobService.GetAllByNoDeptId(orgEntity.Department.DepartmentId);
            bool jobFlag = true;
            if(orgEntity.OrgEntity==null)
            {
                orgEntity.OrgEntity = this.GetById<OrganizationsEntity>(orgEntity.Department.OrgId);
            }
           
            List<RelationUserEntity> lstUserDepart = new List<RelationUserEntity>();
            foreach (var job in orgEntity.JobData)
            {
                string jobError = "";
                if (!CheckJob(orgEntity, job, jobAll, ref jobError))
                {
                    strError += "\r\n" + jobError;
                    jobFlag = false;
                }
                if (job.JobFunctionType == 0&&lstUserDepart.FindIndex(x=>x.UserId.Equals(job.SourceId))<=0)
                {
                  var result= lstUserDepart.Where(x => x.UserId.Equals(job.SourceId) && x.ResourceId == orgEntity.Department.DepartmentId && x.RelationType == RelationUserType.Dept.GetHashCode()).FirstOrDefault();
                    if (result == null||!job.IsDeleted)
                    {
                        //添加用户与部门的关系
                        lstUserDepart.Add(new RelationUserEntity
                        {
                            RelationUserId = job.JobFunctionId,
                            UserId = job.SourceId,
                            ResourceId = orgEntity.Department.DepartmentId,
                            RelationType = RelationUserType.Dept.GetHashCode(),
                            IsDeleted = job.IsDeleted,
                            IsPrimary = job.IsPrimary
                        });
                    }
                }
            }
            if (!jobFlag)
            {
                return false;
            }
            var logService = new DeptCheckLogService();
            DeptCheckLogEntity logEntity = null;
            if (!orgEntity.Department.IsNewAdd)
            {
                logEntity = logService.GetLogEntity(orgEntity.Department.DepartmentId, 0);
                if (logEntity == null)
                {
                    strError = "数据异常，无法删除";
                    return false;
                }
            }
            else
            {
                logEntity = logService.Save(orgEntity.Department.DepartmentId, orgEntity.Department.DepartmentName, 0, ref strError);
            }
           
            var childrenDept = orgEntity.JobData.Where(x => x.JobFunctionType == 1).ToList();
            List<DepartmentEntity> lstchildren = new List<DepartmentEntity>();
            orgEntity.Department.IsCheckOut = false;
            orgEntity.Department.CheckOutUserId = "";
            orgEntity.Department.CheckOutIp = "";

            orgEntity.Department.LastModifyDate = DateTime.Now;
            var deptEntity = orgEntity.Department;
            if (!CheckInChildrenDept(deptService, childrenDept, ref deptEntity, ref lstchildren, ref strError))
            {
                return false;
            }
            orgEntity.Department = deptEntity;
            orgEntity.Department.Chart = orgEntity.ToJson();
            if (!OnDeptEventHandler("checkin", ref orgEntity, ref strError))
            {
                return false;
            }
            string[] relationUsers = null;
            if (lstUserDepart != null && lstUserDepart.Count > 0)
            {
                relationUsers = (from a in lstUserDepart where a.IsPrimary && !a.IsDeleted select a.UserId).ToArray();
            }
            using (var tran = DbRepository.Begin())
            {
                try
                {

                    DbRepository.SaveOrUpdate(orgEntity.Department);
                    DbRepository.Update<DepartmentEntity>(new DepartmentEntity()
                    {
                        ParentId = null
                    },Expression.Eq(DepartmentEntity.__ParentId, orgEntity.Department.DepartmentId));
                    if (lstchildren != null && lstchildren.Count > 0)
                    {
                        DbRepository.BatchSave<DepartmentEntity>(lstchildren);
                    }

                    DbRepository.Delete<JobFunctionEntity>(Expression.Eq(JobFunctionEntity.__DepartmentId, orgEntity.Department.DepartmentId), false);
                 //  DbRepository.Delete<JobFunctionEntity>(typeof(JobFunctionEntity), JobFunctionEntity.__DepartmentId + "='" + orgEntity.Department.DepartmentId + "'", false);
                    DbRepository.BatchInsert<JobFunctionEntity>(orgEntity.JobData,ref strError);
                    var deptWhere = Expression.And(Expression.Eq(RelationUserEntity.__ResourceId, orgEntity.Department.DepartmentId), Expression.Eq(RelationUserEntity.__RelationType, RelationUserType.Dept.GetHashCode()));
                    //删除该部门下用户关系
                    DbRepository.Delete<RelationUserEntity>(deptWhere, false);
                    if (relationUsers != null&& relationUsers.Length>0)
                    {
                        DbRepository.Update<RelationUserEntity>(new RelationUserEntity()
                        {
                            IsPrimary = false
                        }, Expression.And(Expression.In(RelationUserEntity.__UserId, relationUsers), Expression.Eq(RelationUserEntity.__RelationType, RelationUserType.Dept.GetHashCode())));
                    }
                    if (lstUserDepart != null && lstUserDepart.Count > 0)
                    {
                        DbRepository.BatchSave<RelationUserEntity>(lstUserDepart);
                    }
                    if (logEntity != null)
                    {
                        logEntity.Status = 1;
                        logEntity.LastModifyDate = DateTime.Now;
                        logEntity.LastModifyUserId = ApplicationEnvironments.DefaultSession.UserId;
                        logEntity.Chart = orgEntity.Department.Chart;
                        DbRepository.SaveOrUpdate(logEntity);
                    }
                    DbRepository.Commit();
                }
                catch (Exception ex)
                {
                    DbRepository.Rollback();
                    throw ex;
                }

            }
            this.TempDeptDelete(deptid);
            return true;
        }

        /// <summary>
        /// 迁入时处理子部门关系
        /// </summary>
        /// <param name="childrenDept"></param>
        /// <param name="deptEntity"></param>
        /// <param name="lstChildren"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool CheckInChildrenDept(DepartmentService deptService,List<JobFunctionEntity> childrenDept, ref DepartmentEntity deptEntity,
            ref List<DepartmentEntity> lstChildren, ref string strError)
        {

            if (childrenDept != null && childrenDept.Count >= 0)
            {
                foreach (var children in childrenDept)
                {
                    if (string.IsNullOrWhiteSpace(children.SourceId))
                        continue;
                    var dept = deptService.GetById(children.SourceId);
                    if (children.IsDeleted)//当删除关系时将该部门的上级部门置空
                    {
                        dept.ParentId = "";
                        dept.DepartmentPath = dept.DepartmentId;
                    }
                    else
                    {
                        dept.ParentId = deptEntity.DepartmentId;
                        dept.DepartmentPath = deptEntity.DepartmentPath + "_" + dept.DepartmentId;

                    }
                    //
                    if (dept != null)
                    {
                        if (!children.IsDeleted && !string.IsNullOrWhiteSpace(deptEntity.DepartmentPath))
                        {
                            if (deptEntity.DepartmentPath.ToLower().Contains(dept.DepartmentPath))
                            {
                                strError = "当前部门已经在" + children.SourceName + "部门下，无法循环挂载部门";
                                return false;
                            }
                        }
                    }
                    else
                    {
                        strError = children.SourceName + "部门不存在，请检查";
                        return false;
                    }
                    if (children.IsDeleted)//当删除关系时将该部门的上级部门置空 并将深度重置
                    {
                        ICriterion criter = Expression.And(Expression.Eq(DepartmentEntity.__OrgId, deptEntity.OrgId), Expression.And(Expression.Eq(DepartmentEntity.__IsDeleted, false),
                            Expression.Like(DepartmentEntity.__DepartmentPath, deptEntity.DepartmentPath + "_", MatchMode.Start)));
                        var lstdept = DbRepository.Query<DepartmentEntity>(criter);
                        if (lstdept != null && lstdept.Count > 0)
                        {
                            foreach (var item in lstdept)
                            {
                                if (item.IsCheckOut)
                                {
                                    strError = item.DepartmentName + "已迁出，请先将该部门迁入后再进行操作";
                                    return false;
                                }
                                if (item.DepartmentId == deptEntity.ParentId)
                                {
                                    item.ParentId = "";
                                }
                                //item.ParentId = "";
                                item.DepartmentPath.Replace(deptEntity.DepartmentId + "_", "");
                            }
                            lstChildren = lstChildren.Union(lstdept).ToList();
                        }
                    }
                    else//当添加关系时将该部门的上级部门重置，以及将下属部门置空
                    {
                        lstChildren.Add(dept);
                        ICriterion criter = Expression.And(Expression.Eq(DepartmentEntity.__OrgId, deptEntity.OrgId), Expression.And(Expression.Eq(DepartmentEntity.__IsDeleted, false),
                                                  Expression.Like(DepartmentEntity.__DepartmentPath, dept.DepartmentPath + "_", MatchMode.Start)));
                        var lstdept = DbRepository.Query<DepartmentEntity>(criter);
                        if (lstdept != null && lstdept.Count > 0)
                        {
                            foreach (var item in lstdept)
                            {
                                if (item.IsCheckOut)
                                {
                                    strError = item.DepartmentName + "已迁出，请先将该部门迁入后再进行操作";
                                    return false;
                                }
                                if (item.DepartmentId == deptEntity.ParentId)
                                {
                                    item.ParentId = "";
                                }
                                item.DepartmentPath = deptEntity.DepartmentId + "_" + item.DepartmentPath;
                            }
                            lstChildren = lstChildren.Union(lstdept).ToList();
                        }
                    }

                }
            }
            return true;
        }

        /// <summary>
        /// 验证单个岗位是否正确
        /// </summary>
        /// <param name="entity">岗位</param>
        /// <param name="jobAll">当前所有正式岗位</param>
        /// <param name="strError">错误信息</param>
        /// <returns></returns>
        public bool CheckJob(OrgChartEntity orgEntity,JobFunctionEntity entity, List<JobFunctionEntity> jobAll, ref string strError)
        {
            if (entity.IsDeleted)
            {
                return true;
            }
            if (entity.JobFunctionType == 1)
            {
                if (entity.DepartmentId == entity.SourceId)
                {
                    strError = entity.JobFunctionId + "岗位下不能包含当前部门";
                    return false;
                }
            }
            if (!CheckValidHelper.CheckVaild(entity, ref strError))
            {
                strError = entity.SourceName + "岗位：" + strError;
                return false;
            }
            if (jobAll != null && jobAll.Count > 0)
            {
                if (entity.JobFunctionType == 1)//验证部门
                {
                    var result = jobAll.Where(x => x.JobFunctionType == 1 && x.SourceId == entity.SourceId).FirstOrDefault();
                    if (result != null)
                    {
                        strError = entity.SourceName + "已经属于" + result.JobFunctionId + "岗位下！";
                        return false;
                    }
                }
                else//验证岗位
                {
                    if (entity.IsPrimary)
                    {
                        var result = jobAll.Where(x => x.JobFunctionType == 0 && x.IsPrimary && x.SourceId == entity.SourceId).FirstOrDefault();
                        if (result != null)
                        {
                            strError = entity.SourceName + "已经在" + result.JobFunctionId + "下设置了主岗！";
                            return false;
                        }
                    }
                }
            }
            return OnJobEventHandler("checkjob",orgEntity,ref entity,ref strError);
        }

        /// <summary>
        /// 撤销迁出
        /// </summary>
        /// <param name="deptid"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool Revoke(string deptid, ref string strError)
        {
            var deptService = new DepartmentService();
          
          
            OrgChartEntity orgEntity = this.ReadOrgChart(deptid);
            if (orgEntity == null )
            {
                strError = "数据格式错误，无法转换";
                return false;
            }
            if (!orgEntity.Department.IsCheckOut || orgEntity.Department.CheckOutUserId != ApplicationEnvironments.DefaultSession.UserId)
            {
                strError = "对不起，您无权操作";
                return false;
            }
            if (orgEntity.Department.IsNewAdd)
            {
                return this.TempDeptDelete(deptid);
            }
            var logService = new DeptCheckLogService();
            DeptCheckLogEntity logEntity = null;
            logEntity = logService.GetLogEntity(orgEntity.Department.DepartmentId, 0);
            if (logEntity == null)
            {
                strError = "数据异常，无法删除";
                return false;
            }
            orgEntity.Department = deptService.GetById(orgEntity.Department.DepartmentId);
            if( orgEntity.Department==null)
            {
                return true;                
            }
            orgEntity.Department.IsCheckOut = false;
            orgEntity.Department.CheckOutUserId = "";
            orgEntity.Department.CheckOutIp = "";
            orgEntity.Department.LastModifyDate = DateTime.Now;
            if (!OnDeptEventHandler("revoke",ref orgEntity, ref strError))
            {
                return false;
            }
            using (var tran = DbRepository.Begin())
            {
                try
                {
                    this.Update(orgEntity.Department);
                   
                    logEntity.Status = 2;
                    logEntity.LastModifyDate = DateTime.Now;
                    logEntity.LastModifyUserId = ApplicationEnvironments.DefaultSession.UserId;
                    this.SaveOrUpdate(logEntity);
                    this.Commit();
                }
                catch (Exception ex)
                {
                    DbRepository.Rollback();
                    throw ex;
                }
            }
            return true;
        }

        /// <summary>
        /// 部门接口事件处理
        /// </summary>
        /// <param name="eventType"></param>
        /// <param name="entity"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool OnDeptEventHandler(string eventType, ref OrgChartEntity entity, ref string strError)
        {
            if (entity == null || entity.Department == null   || entity.OrgEntity == null)
            {
                strError = "参数错误";
                return false;
            }
            if (string.IsNullOrWhiteSpace(entity.OrgEntity.EventHandler))
            {
                return true;
            }
            string[] ass = entity.OrgEntity.EventHandler.Split(new char[] { ';', ',' });
            //var eventHandler = CacheService.Get<IOrgEventHandler>(CACHE_ORGCHART_IEVENTHANDLER + entity.Department.OrgEntity.EventHandler, () =>
            //{
            //    object ieventHandler = ReflectionHelper.CreateInstance(ass[0], ass[1]);
            //    if (ieventHandler is IOrgEventHandler)
            //    {
            //        return (ieventHandler as IOrgEventHandler);
            //    }
            //    return null;
            //});
            //if (eventHandler != null)
            //{
            //    switch (eventType.ToLower())
            //    {
            //        case "checkout":
            //            return eventHandler.CheckOut(ref entity, ref strError);
            //        case "checkin":
            //            return eventHandler.CheckIn(ref entity, ref strError);
            //        case "deptsaved":
            //            return eventHandler.DeptTempSave(ref entity, ref strError);
            //        case "revoke":
            //            return eventHandler.DeptRevoke(ref entity, ref strError);
            //    }
            //}
            return true;
        }
        #endregion

        #region 岗位
        /// <summary>
        /// 获取岗位对象
        /// </summary>
        /// <param name="entity">初始岗位参数</param>
        /// <param name="strError">错误信息</param>
        /// <returns></returns>
        public JobFunctionEntity GetJobById(JobFunctionEntity entity,ref string strError)
        {
            if (string.IsNullOrWhiteSpace(entity.DepartmentId))
            {
                strError = "参数错误";
                return entity;
            }
           
            var orgEntity = GetOrgById(entity.DepartmentId);
            if (orgEntity == null)
            {
                strError = "参数错误";
                return entity;
            }
            if (entity == null)
            {
                strError = "参数错误";
                return null;
            }
            if (entity.JobFunctionId == null)
            {
                entity.JobFunctionId = "";
            }
            //if (!orgEntity.Department.IsCheckOut || !orgEntity.Department.CheckOutUserId.Equals(ApplicationEnvironments.DefaultSession.UserId))
            //{//当前部门迁出并且迁出用户是当前用户时取xml数据
            //    return false;
            //}
            if (!string.IsNullOrWhiteSpace(entity.JobFunctionId))
            {
                string jobid = entity.JobFunctionId.Trim();
                if (orgEntity.JobData != null && orgEntity.JobData.Count > 0)
                {
                    var oldEntity = orgEntity.JobData.Where(x => x.JobFunctionId.Equals(jobid.Trim())).FirstOrDefault();
                    if (oldEntity != null)
                    {
                        entity = oldEntity;
                    }
                }
            }
            entity.JobGradeId = entity.JobGradeId == null ? "" : entity.JobGradeId;
            entity.ParentId = entity.ParentId == null ? "" : entity.ParentId;
             entity.SourceName = entity.SourceName == null ? "" : entity.SourceName;
             entity.SourceId = entity.SourceId == null ? "" : entity.SourceId;
            
            return entity;
        }

        /// <summary>
        /// 获取jobfunctionid
        /// </summary>
        /// <param name="jobId">jobfunctionid</param>
        /// <param name="deptId">部门Id</param>
        /// <returns></returns>
        public bool SaveJobFunction(ref JobFunctionEntity entity, ref string strError)
        {
            if (string.IsNullOrWhiteSpace(entity.DepartmentId))
            {
                strError = "参数错误";
                return false;
            }
            var orgEntity = GetOrgById(entity.DepartmentId);
            if (orgEntity == null)
            {
                strError = "参数错误";
                return false;
            }
            JobFunctionService jobService = new JobFunctionService();
            if (!orgEntity.Department.IsCheckOut || !orgEntity.Department.CheckOutUserId.Equals(ApplicationEnvironments.DefaultSession.UserId))
            {//当前部门迁出并且迁出用户是当前用户时取xml数据
                strError = "用户尚未迁出或者迁出者不是本人";
                return false;
            }
            entity.OrgId = orgEntity.Department.OrgId;
            if (!CheckJobFunction(entity, orgEntity.JobData, ref strError))
            {
                return false;
            }
            bool isAdd = false;
            entity.LastModifyDate = DateTime.Now;
            entity.LastModifyUserId = ApplicationEnvironments.DefaultSession.UserId;
            if (orgEntity.JobData != null && orgEntity.JobData.Count > 0)
            {
                string jobid = entity.JobFunctionId == null ? "" : entity.JobFunctionId.Trim();
                var i = orgEntity.JobData.FindIndex(x => x.JobFunctionId.Equals(jobid));
                if (i >= 0)
                {
                    orgEntity.JobData[i] = entity;
                }
                else
                {
                    isAdd = true;
                }
            }
            else
            {
                orgEntity.JobData = new List<JobFunctionEntity>();
                orgEntity.JobData.Add(entity);
            }
            if (string.IsNullOrWhiteSpace(entity.JobFunctionId))
            {
                entity.JobFunctionId = jobService.CreateJobFunctionIdByDeptId(entity.DepartmentId, ref strError);
            }
            if (isAdd)
            {
                entity.IsAdd = true;
                entity.CreateDate = DateTime.Now;
                entity.CreateBy = ApplicationEnvironments.DefaultSession.UserId;
                orgEntity.JobData.Add(entity);
            }
            return this.SaveFile(orgEntity, ref strError);

        }

        
        /// <summary>
        /// 验证当前岗位有效性
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="jobData"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool CheckJobFunction(JobFunctionEntity entity ,List<JobFunctionEntity> jobData,ref string strError)
        {
            if (entity.JobFunctionType == 1)
            {
                if (entity.SourceId == entity.DepartmentId)
                {
                    strError = "当前岗位不能管理当前部门";
                    return false;
                }
            }
            var result = jobData.Where(x => !x.IsDeleted && !string.IsNullOrWhiteSpace(x.ParentId) && x.ParentId.Equals(entity.ParentId)).ToList();
               if (result != null && result.Count > 0)
               {
                   if (entity.JobFunctionType != 1)//用户验证
                   {
                       if (result.Where(x => !string.IsNullOrWhiteSpace(x.SourceId) && x.SourceId.Equals(entity.SourceId) && x.JobFunctionId != entity.JobFunctionId).FirstOrDefault() != null)
                       {
                           strError = "用户在同一级别时不能同时存在2个岗位";
                           return false;
                       }
                   }
               }
               if (entity.JobFunctionType != 1)//岗位验证
               {
                   if (entity.IsPrimary)
                   {
                       ///主岗验证
                       var primaryResult = jobData.Where(x => !x.IsDeleted && !string.IsNullOrWhiteSpace(x.SourceId) && x.SourceId.Equals(entity.SourceId) && x.IsPrimary && x.JobFunctionId != entity.JobFunctionId).FirstOrDefault();
                       if (primaryResult != null)
                       {
                           strError = "用户主岗已经存在于" + primaryResult.JobFunctionName + "下";
                           return false;
                       }
                   }
               }
               else//部门验证
               {
                   var primaryResult = jobData.Where(x => !x.IsDeleted && !string.IsNullOrWhiteSpace(x.SourceId) && x.SourceId.Equals(entity.SourceId) && x.JobFunctionId != entity.JobFunctionId).FirstOrDefault();
                   if (primaryResult != null)
                   {
                       strError = "部门已经属于已经" + primaryResult.JobFunctionName + "管理，不能在挂在当前岗位下";
                       return false;
                   }
               }
            return true;
        }

        /// <summary>
        /// 岗位删除
        /// </summary>
        /// <param name="jobFuntionId">岗位id</param>
        /// <param name="deptId">部门id</param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool JobDelete(string jobFuntionId, string deptId, ref string strError)
        {
            if (string.IsNullOrWhiteSpace(deptId) || string.IsNullOrWhiteSpace(jobFuntionId))
            {
                strError = "参数错误";
                return false;
            }
            var orgEntity = GetOrgById(deptId);
            if (orgEntity == null)
            {
                strError = "参数错误";
                return false;
            }
            if (orgEntity.JobData != null && orgEntity.JobData.Count > 0)
            {
                if (orgEntity.JobData != null && orgEntity.JobData.Count > 0)
                {
                    if (orgEntity.JobData.Where(x => !string.IsNullOrWhiteSpace(x.ParentId) && x.ParentId.Equals(jobFuntionId)).FirstOrDefault() != null)
                    {
                        strError = "该岗位下其它岗位删除后在进行操作";
                        return false;
                    }
                    var index = orgEntity.JobData.FindIndex(x => x.JobFunctionId.Equals(jobFuntionId));
                    if (index >= 0)
                    {
                        var job = orgEntity.JobData[index];
                        if (job != null && string.IsNullOrWhiteSpace(job.ParentId))
                        {
                            strError = "顶级节点无法删除！";
                            return false;
                        }
                        orgEntity.JobData.Remove(job);
                    }
                }
                return this.SaveFile(orgEntity, ref strError);
            }
            return false;
        }

        /// <summary>
        /// 岗位接口
        /// </summary>
        /// <param name="eventType"></param>
        /// <param name="entity"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool OnJobEventHandler(string eventType,OrgChartEntity orgEntity, ref JobFunctionEntity entity, ref string strError)
        {
            if (orgEntity == null || orgEntity.Department == null || orgEntity.OrgEntity == null)
            {
                strError = "参数错误";
                return false;
            }
            if (string.IsNullOrWhiteSpace(orgEntity.OrgEntity.EventHandler))
            {
                return true;
            }
            string[] ass = orgEntity.OrgEntity.EventHandler.Split(new char[] { ';', ',' });
            //var eventHandler = CacheFactory.Get<IOrgEventHandler>(CACHE_ORGCHART_IEVENTHANDLER + orgEntity.Department.OrgEntity.EventHandler, () =>
            //{
            //    object ieventHandler = ReflectionHelper.CreateInstance(ass[0], ass[1]);
            //    if (ieventHandler is IOrgEventHandler)
            //    {
            //        return (ieventHandler as IOrgEventHandler);
            //    }
            //    return null;
            //});
            //if (eventHandler != null)
            //{
            //    switch (eventType.ToLower())
            //    {
            //        case "checkjob":
            //            return eventHandler.CheckJob(orgEntity, ref entity, ref strError);

            //    }
            //}
            return true;
        }
        #endregion

        #region
        public LigerGrid GetUsers(LigerGrid ligerGrid)
        {
            string sql = "select distinct b.RealName,b.UserName,b.UserId from ORG_JobFunction as a inner join ORG_User as b on a.SourceId = b.UserId where a.IsDeleted=0 {0} ";

            ICriterion criter = Expression.And(Expression.Eq("a." + JobFunctionEntity.__JobFunctionType,JobFunctionType.JobFunction.GetHashCode()),
                Expression.Eq("a."+JobFunctionEntity.__OrgId,ligerGrid.GetValue(JobFunctionEntity.__OrgId)) );
            if (!string.IsNullOrEmpty(ligerGrid.keyWord))
            {
                criter = Expression.And(criter,

                           Expression.Like(new string[] {
                                "b."+UserEntity._PrimaryKeyName ,
                                 "b."+UserEntity.__UserName ,
                                  "b."+UserEntity.__RealName,
                                   "b."+UserEntity.__Email,
                                    "b."+UserEntity.__Phone,
                           }, ligerGrid.keyWord)
                           );
            }
            return DbRepository.Query<UserEntity>(sql,ligerGrid, criter);
        }

        /// <summary>
        ///  通过组织架构编号获取下级部门
        /// </summary>
        /// <param name="parentId">上级id</param>
        /// <param name="orgId">组织架构</param>
        /// <param name="iscurrentDept">当前值是否是部门</param>
        /// <param name="isloadjob">是否加载岗位</param>
        /// <returns></returns>
        public List<DepartmentEntity> GetDeptByOrgId(string parentId, string orgId,bool iscurrentDept,int isloadjob)
        {
            ICriterion criter = Expression.Eq(DepartmentEntity.__IsDeleted, false);
            if (string.IsNullOrWhiteSpace(parentId))
            {
                criter = Expression.And(criter, Expression.And(Expression.Eq(DepartmentEntity.__OrgId, orgId),
              Expression.Or(Expression.Eq(DepartmentEntity.__ParentId, ""), Expression.IsNull(DepartmentEntity.__ParentId))));
            }
            else
            {
                criter = Expression.And(criter, Expression.Eq(DepartmentEntity.__ParentId, parentId));
            }
            var lstEntity = DbRepository.Query<DepartmentEntity>(criter, new Order(DepartmentEntity.__OrderNum, true)).ToList();
            if (lstEntity == null)
            {
                lstEntity = new List<DepartmentEntity>();
            }
            if (isloadjob > 0)
            {
                var lstTempEntity = new JobFunctionService().GetJobFunctionByParent(orgId, iscurrentDept?"": parentId);
                if (lstTempEntity != null && lstTempEntity.Count > 0)
                {
                    var lst = (from x in lstTempEntity
                               select new DepartmentEntity
                               {
                                   DepartmentId = x.JobFunctionId,
                                   ParentId = !string.IsNullOrWhiteSpace(x.ParentId) ? x.ParentId : x.DepartmentId,
                                   parent = !string.IsNullOrWhiteSpace(x.ParentId) ? x.ParentId : x.DepartmentId,
                                   DepartmentName = x.JobFunctionName,
                                   children = true,
                                   IsEdited=true
                               });
                    lstEntity = lstEntity.Union(lst).ToList();
                }
            }
            lstEntity.ForEach(x => {
                x.parent = !string.IsNullOrWhiteSpace(parentId) ? parentId : "#";
                x.children = true;
            });
            //if (lstEntity.Count > 0)
            //{
            //    lstEntity.ForEach(item => {
            //        item.parent = string.IsNullOrWhiteSpace(item.ParentId) ? orgId : item.ParentId;
            //        item.IsEdited = false;

            //        item.LstChildren = DbRepository.Query<DepartmentEntity>(Expression.And(Expression.Eq(DepartmentEntity.__IsDeleted, false),
            //  Expression.Eq(DepartmentEntity.__ParentId, item.DepartmentId))).ToList();
            //        item.children = item.LstChildren != null && item.LstChildren.Count > 0;
            //    });
            //}
            return lstEntity.OrderBy(x => x.OrderNum).ToList();
        }
        #endregion


    }
}
